/**
 * 
 */
package data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;

import domain.Article;
import domain.Product;
import domain.User;
import domain.Vote;

/**
 * @author grupo22
 *
 */
public class JDBCVoteDAO implements IVoteDAO {

	/* (non-Javadoc)
	 * @see data.IVoteDAO#selectAllVotes()
	 */
	@Override
	public Collection selectAllVotes() {
		Collection result = new LinkedList();
		
		Connection con = ConnectionManager.getInstance().checkOut();
		PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
        	String sql = "SELECT * FROM Vote;";
        	stmt = con.prepareStatement(sql);
            
            rs = stmt.executeQuery();

            while (rs.next()) {
            	String OIDProduct = new String(rs.getString("OIDProduct"));
            	String OIDUser = new String(rs.getString("OIDUser"));
            	IProductDAO pdao = new JDBCProductDAO();
            	IUserDAO udao = new JDBCUserDAO();
            	Product p = pdao.select(con, OIDProduct);
            	User u = udao.select(con, OIDUser);
            	Vote v = new Vote(u,p);
                result.add(v);
            }
        } catch (SQLException e) {
            System.out.println("Message: Fallo en JDBCVoteDAO.selectAllVotes " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
        	ConnectionManager.getInstance().checkIn(con);
        	try {
                    if (rs != null)
                            rs.close();
                    if (stmt != null)
                            stmt.close();
            } catch (SQLException e) {}
        }

		return result;
	}
	@Override
	public void insert(Vote v){
		Connection con = ConnectionManager.getInstance().checkOut();
		PreparedStatement stmt = null;
        try {
        	String sql = "INSERT INTO Vote (OIDProduct, OIDUser) VALUES (?, ?)";
        	stmt = con.prepareStatement(sql);
        	IProductDAO pdao = new JDBCProductDAO();
        	IUserDAO udao = new JDBCUserDAO();
        	
        	stmt.setString(1, pdao.selectOID(con, v.getProduct().getBrand(), v.getProduct().getModel()));
        	stmt.setString(2, udao.selectOID(con, v.getUser().getId()));
        	System.out.println("Sentencia: " + stmt.toString());
        	
            stmt.executeUpdate();
        } catch (SQLException e) {
            System.out.println("Message: Fallo en JDBCVoteDAO.insert " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
        	ConnectionManager.getInstance().checkIn(con);
        	try {
        		if (stmt != null)
        			stmt.close();
            } catch (SQLException e) {}
        }
		
	}
}
